package com.sx.first.dao;

import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

import com.sx.first.dao.PositionDAO;
import com.sx.first.model.Position;

@Repository("positionDAO")
@Scope("prototype")
public class PositionDAO {
	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public List<Position> findAll() {
		@SuppressWarnings("unchecked")
		List<Position> list = sessionFactory.getCurrentSession().createQuery("from Position").list();
		return list;
	}
	
	
	
	public void save(Position pos){
		sessionFactory.getCurrentSession().save(pos);
	}
	
	public void delete(Position pos){
		sessionFactory.getCurrentSession().delete(pos);
	}
	
	public void update(Position pos) {
		sessionFactory.getCurrentSession().update(pos);
	}
	
	
	public Position findById(int posId) {
		return sessionFactory.getCurrentSession().get(Position.class, posId);
	}



	public List<Position> findAllByDepId(Integer depId) {
		@SuppressWarnings({"unchecked" })
		List<Position> list = sessionFactory
				.getCurrentSession()
				.createQuery("from Position as p where p.dep.depId = :depId order by p.posId desc")
				.setParameter("depId", depId).list();
		for (Position position : list) {
			Hibernate.initialize(position.getDep());
		}
		return list;
	}
	


}
